<?php
/**
 * alltosun.com 微信授权控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址:   http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 李维 (liw@alltosun.com) $
 * $Date: 2014-1-15 下午12:56:57 $
 * $Id$
*/

class Action
{
    private $user_id;
    private $appid; // qq互联ID
    private $appkey;
    private $callback;

    public function __construct()
    {
        $this->user_id = user_helper::get_user_id();
        $openapi = Config::get('openapi');
        $this->appid = $openapi['weixin'][0];
        $this->appkey = $openapi['weixin'][1];
        $this->callback = $openapi['weixin'][2];
    }

    /**
     * ——call处理登录和同步授权问题
     * @param $action 开放平台name
     * @param $params 参数数组 callback
     * @author liw add 2012-09-21
     * @return string
     */
    public function __call($action = '', $params = array())
    {
        $isBind = Request::Get('bind', '0');
        if($isBind) {
            $_SESSION['bind'] = $isBind;
            if(!user_helper::get_user_id()) {
                return array('您需要先登录才可以绑定第三方帐号。', 'error', AnUrl('user/login'));
            }
            if(!user_helper::is_perfect_by_id(user_helper::get_user_id())) {
                return array('请完善信息后才可以绑定其他帐号。', 'error', AnUrl('openapi/index/bind'));
            }
        } else {
            $_SESSION['bind'] = 0;
        }
        if(!isset($_SESSION['login_callback'])) {
            $_SESSION['login_callback'] = user_helper::get_jump_url($rfUrl);
        }
        // scope/ state
        $scope      = Request::Get('scope', '');
        $return_url = Request::Get('return_url', '');
        $scope = 'snsapi_userinfo';
        // $return_url = urlencode(AnUrl('openapi/weixin/index/successLogin'));
        $return_url = urlencode(AnUrl(''));
        // 跳转到www
        $_SESSION['weixin_oauth2_state'] = user_helper::random_hash(5);
        $_SESSION['wx_oauth_return_url'] = $return_url;

        $check_info = AnOpenApi('weixin')->authorize($scope, $_SESSION['weixin_oauth2_state'], '');
        if ($check_info['status'] == 'ok') {
            $user_id = user_helper::get_user_id();
            $return_info = $this->user_login($this->user_id);
            if($return_info['info'] != 'error') {
                echo $return_info;
            } else {
                return array('微信登录失败，请重试！', 'error', AnUrl('user/login'));
            }
        } else {
            Response::redirect($check_info['url']);
        }
    }

    /**
     * 回调
     */
    public function callback()
    {
        $action = "weixin";
        $code = Request::Get('code', '');
        if (!$code) {
            return '对不起，授权信息错误[1]';
        }

        // state
        if (empty($_SESSION['weixin_oauth2_state']) || $_SESSION['weixin_oauth2_state'] != Request::Get('state')) {
            return '授权失败[2]';
        }

        // 获取return url
        $return_url = '';
        if(!empty($_SESSION['wx_oauth_return_url'])) {
            $return_url = $_SESSION['wx_oauth_return_url'];
        }

        // 生成connect
        try {
            //$connect_info = AnOpenApi($action)->callback($code);
            $request_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appkey."&code=".$code."&grant_type=authorization_code";
            $str  = curl_request($request_url, 'get');
            $info = json_decode($str, true);
            $connect_user_info = AnOpenApi($action)->getUserInfo($info['access_token'], $info['openid']);
            $connect_info = _uri('connect_weixin', array('unionid'=>$connect_user_info['unionid']));
            $connect_user_info['avatar'] = $this->get_big_avatar_url($connect_user_info['headimgurl']);
            $connect_user_info['user_name'] = $connect_user_info['nickname'];
            if (!$connect_info) {
                $connect_info_create = array(
                        'unionid'                =>    $connect_user_info['unionid'],
                        'connect_open_id'        =>    $info['openid'],
                        'connect_site_id'        =>    6,
                        'connect_nick_name'      =>    $connect_user_info['nickname'],
                        'scope'                  =>    'snsapi_userinfo',
                        'access_token'   =>    $info['access_token'],
                        'refresh_token'  =>    $info['refresh_token'],
                        'expires_time'   =>    $info['expires_in']+time()
                );
                if($_SESSION['bind']) {
                    if(!user_helper::get_user_id()) {
                        return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                    }
                    $connect_info_create['user_id'] = user_helper::get_user_id();
                    $connect_id = _model('connect_weixin')->create($info);
                    if($connect_id) {
                        unset($_SESSION['bind']);
                        return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                    }
                }
                $connect_id = _model('connect_weixin')->create($connect_info_create);
                $_SESSION['associatedConnectInfo']['id'] = $connect_id;
                $_SESSION['associatedConnectInfo']['type'] = 'weixin';
                $_SESSION['associatedConnectInfo']['user_info'] = $connect_user_info;
                Response::redirect(AnUrl('openapi/choose_bind'));
            } else {
                $connect_update_info = array(
                        'connect_nick_name'      =>    $connect_user_info['nickname'],
                        'connect_open_id' => $info['openid'],
                        'access_token'   =>    $info['access_token'],
                        'refresh_token'  =>    $info['refresh_token'],
                        'expires_time'   =>    $info['expires_in']+time()
                );
                _model('connect_weixin')->update($connect_info['id'], $connect_update_info);

                if(!$connect_info['user_id']) {
                    if($_SESSION['bind']) {
                        if(!user_helper::get_user_id()) {
                            return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                        }
                        $affected = _model('connect_weixin')->update($connect_info['id'], array('user_id' => user_helper::get_user_id()));
                        if($affected) {
                            unset($_SESSION['bind']);
                            return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                        }
                    }

                    $_SESSION['associatedConnectInfo']['id'] = $connect_info['id'];
                    $_SESSION['associatedConnectInfo']['type'] = 'weixin';
                    $_SESSION['associatedConnectInfo']['user_info'] = $connect_user_info;
                    Response::redirect(AnUrl('openapi/choose_bind'));
                } else {
                    if($_SESSION['bind']) {
                        unset($_SESSION['bind']);
                        return array('此微信帐号已经被其他帐号绑定过了', 'error', AnUrl('user/setting/account_bind'));
                    }
                    $this->user_id = $connect_info['user_id'];
                    $user_info = _uri('user', $this->user_id);
                    $info = array(
                            'nickname'         =>    $connect_user_info['nickname'],
                            'nickname_base64'  =>    base64_encode($connect_user_info['nickname']),
                            'last_login_time'  =>    date('Y-m-d H:i:s', time())
                    );
                    if(empty($user_info['nickname'])) {
                        $info['nickname'] = $connect_user_info['nickname'];
                    }
                    if(empty($user_info['avatar'])) {
                        $info['avatar'] = $this->get_big_avatar_url($connect_user_info['headimgurl']);
                    }
                    _model('user')->update($connect_info['user_id'], $info);
                    $return_info = $this->user_login($user_info['id']);
                    if($return_info['info'] != 'error') {
                        echo $return_info;
                    } else {
                        return array('微信登录失败，请重试！', 'error', AnUrl('user/login'));
                    }

                }
            }
        } catch (Exception $e) {
            // if (ONDEV) {

            // }
            echo $e->getMessage();
            return '对不起，授权失败[3]';
        }
        if (!$connect_info) {
            return '抱歉，授权失败[4]';
        }
    }

    /**
     * 获取大头像
     */
    private function get_big_avatar_url($url)
    {
        if(!$url) {
            return '';
        }

        $url = preg_replace('/\/\d+$/', '/0', $url);

        return $url;
    }

    private function connect_update($connect_info, $user, $user_id = 0)
    {
        $info = array(
            'connect_open_id'  =>    $user['openid'],
            'access_token'     =>    $user['access_token'],
            'expires_time'     =>    $user['expires_in']+time(),
            'refresh_token'    =>    $user['refresh_token']
            );
        if($user_id) {
            $info['user_id'] = $user_id;
        }
        _model('connect_weixin')->update($connect_info['id'], $info);
    }

    private function user_login($user_id)
    {
        // 本站登录，写入session
        $user_info = _uri('user', $user_id);
        user_helper::session_update($user_info, 'weixin');

        //同步登录ucenter
        $callback = $_SESSION['login_callback'];
        $return_info = user_helper::uc_login($user_info['uc_id'], '', $callback,0,1);
        return $return_info;
    }
}
?>